package com.huangtang.pc.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;

/**
 * @author sunjf
 * @date 2024/01/11
 */
@Slf4j
@Configuration
@AllArgsConstructor
public class ThreadPoolConfig implements AsyncConfigurer {


    /**
     * 延时线程池，注册为Spring中的Bean
     * @return 延迟线程池
     */
    @Bean
    public ScheduledThreadPoolExecutor scheduledThreadPoolExecutor(){
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("scheduledThread-%d").build();
        return new ScheduledThreadPoolExecutor(getAvailableProcessors(),threadFactory);
    }

    /**
     * 获取虚拟机可用的处理数
     *
     * @return int
     */
    private int getAvailableProcessors() {
        int corePoolSize;
        try {
            corePoolSize = Runtime.getRuntime().availableProcessors();
        } catch (Exception e) {
            log.error("获取虚拟机可用的处理数失败：{}", e.getMessage());
            corePoolSize = 4;
        }
        return corePoolSize;
    }

}
